package com.fh.service.impl;

import com.fh.entity.Cart;
import com.fh.service.CartService;
import com.fh.sku.entity.SkuStock;
import com.fh.sku.service.SkuStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import utils.RedisKey;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private SkuStockService skuStockService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Cart addCart(Cart cart, String phone) {
        cart.setSkuCode("201808270027001");
      SkuStock skuStock= skuStockService.queryProuctPriceBySkuCode(cart.getSkuCode());
      cart.setPrice(skuStock.getPrice());
        //价格乘以数量 计算出小计
      cart.setSubtotal(cart.getPrice().multiply(new BigDecimal(cart.getCount())));
      cart.setCheckStatus(true);
      String cartKey = RedisKey.getCartKey(phone);
      //判断购物车中有没有该商品
      if(redisTemplate.opsForHash().hasKey(cartKey,cart.getSkuCode())){
         Cart car = (Cart) redisTemplate.opsForHash().get(cartKey,cart.getSkuCode());
         cart.setCount(car.getCount()+cart.getCount());
         cart.setSubtotal(car.getPrice().multiply(new BigDecimal(cart.getCount())));
         cart.setCheckStatus(true);

      }
      redisTemplate.opsForHash().put(cartKey,cart.getSkuCode(),cart);
      return  cart;




    }

    @Override
    public Long getCount(String phone) {
        String cartKey = RedisKey.getCartKey(phone);
        Long count = redisTemplate.opsForHash().size(cartKey);
        return  count;
    }

    @Override
    public List<Cart> getCar(String phone) {
        String cartKey = RedisKey.getCartKey(phone);
        return  redisTemplate.opsForHash().values(cartKey);
    }

    @Override
    public void updateProductCount(Cart cart, String phone) {
        String cartKey = RedisKey.getCartKey(phone);
        Cart car = (Cart) redisTemplate.opsForHash().get(cartKey, cart.getSkuCode());
        car.setCount(cart.getCount());
        car.setSubtotal(car.getPrice().multiply(new BigDecimal(cart.getCount())));
       redisTemplate.opsForHash().put(cartKey,cart.getSkuCode(),car);


    }

    @Override
    public void deleteBatch(String s, String phone) {
        String cartKey = RedisKey.getCartKey(phone);
        redisTemplate.opsForHash().delete(cartKey,s);

    }
}
